import ajax from '@util/ajax.ts'
import { Result } from '@src/interfaces/TypeResult.ts'

/**
 * 上传图片
 * @param file
 * @param uploadProgress
 */
export async function uploadImageApi(
  file: File,
  uploadProgress?: (progress: number) => void,
) {
  const formData = new FormData()
  formData.append('file', file)

  return ajax({
    timeout: 0,
    method: 'post',
    url: '/image/upload',
    data: formData,
    headers: {
      'Content-Type': 'multipart/form-data',
    },
    onUploadProgress: ({ loaded, total }) => {
      // @ts-ignore
      let progress = Math.floor((loaded / total) * 100)
      Number.parseInt(progress.toFixed(2))
      uploadProgress?.(progress)
    },
  }).then((res) => {
    return res.data as Result<string>
  })
}

/**
 * 根据图片名称获取图片地址
 * @param imageName 图片名称
 */
export function getImageUrlByImageName(imageName: string) {
  const baseUrl = 'http://localhost:8080/image/'
  return `${baseUrl}${imageName}`
}
